import React from 'react'
import cssStyle from './index.module.css'
import PropTypes from 'prop-types'

class Model extends React.PureComponent{
    modelRef = React.createRef()
    timer = null
    onClick = e => {
        if(this.modelRef.current === e.target){
            this.props.onClick()
        }
    }
    bodyScroll = event => {
        event.preventDefault()
    }
    open = () => {
        this.modelRef.current.removeEventListener('click', this.onClick)
        // window.removeEventListener('mousewheel', this.bodyScroll)
        // window.removeEventListener('touchmove', this.bodyScroll)
        this.modelRef.current.addEventListener('click', this.onClick)
        // window.addEventListener('mousewheel', this.bodyScroll, { passive: false })
        // window.addEventListener('touchmove', this.bodyScroll, { passive: false })
        if(this.timer){
            clearTimeout(this.timer)
            this.timer = null
        }
        this.modelRef.current.style.background = 'rgba(0, 0, 0, 0.2)'
        this.modelRef.current.style.zIndex = 999
    }
    close = () => {
        this.modelRef.current.removeEventListener('click', this.onClick)
        // window.removeEventListener('mousewheel', this.bodyScroll)
        // window.removeEventListener('touchmove', this.bodyScroll)
        if(this.timer){
            clearTimeout(this.timer)
            this.timer = null
        }
        this.modelRef.current.style.background = 'rgba(0, 0, 0, 0)'
        this.timer = setTimeout(() => {
            this.modelRef.current.style.zIndex = -1
            this.timer = null
        }, 300)
    }
    componentWillUnmount(){
        this.modelRef.current.removeEventListener('click', this.onClick)
    }
    render(){
        return(
            <div ref={ this.modelRef } className={ cssStyle.model }>
                { this.props.children }
            </div>
        )
    }
}

Model.propTypes = {
    children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
    onClick: PropTypes.func
}

export default Model